package tools

import (
	"bytes"
	"encoding/json"
	"github.com/wechatpay-apiv3/wechatpay-go/core/consts"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"xialou_platform/app/jwtx"
)

func Post(url string, req interface{}) (*http.Response, error) {
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	if err := enc.Encode(req); err != nil {
		return nil, err
	}
	var reader io.Reader
	reader = &buf
	do, err := http.DefaultClient.Post(url, consts.ApplicationJSON, reader)
	if err != nil {
		return nil, err
	}
	return do, nil
}

// RequestOtherPlatform 请求其他平台接口
func RequestOtherPlatform(url, method, AccessSecret, reqStr string, AccessExpire, agentId int64) ([]byte, error) {
	reqBody := strings.NewReader(reqStr)

	request, err := http.NewRequest(method, url, reqBody)
	if err != nil {
		return nil, err
	}
	if method != "GET" {
		request.Header.Add("content-type", "application/json")
	}
	accessToken, err := jwtx.GetToken(AccessSecret, time.Now().Unix(), AccessExpire, agentId, agentId)
	if err != nil {
		return nil, err
	}
	request.Header.Add("Authorization", accessToken)

	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

type CommonResp[T any] struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    T      `json:"data"`
}
